import React, { useReducer, useEffect, useState } from 'react'
import { Tabs, Modal, message } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import style from './Index.module.less'
import { reducer, initialState } from './reducer'
import { awaitWrap } from '@js/tool'
import { getDictionaryRequest, getThemeListRequest, delThemeRequest, addThemeRequest, getStaffsRequest, getNotariesRequest, getArbitratorsRequest, getAddressListRequest } from './ajax'
import AddThemeModal from './components/AddThemeModal'
import FinishThemeModal from './components/FinishThemeModal/Index'
import MainTable from './components/MainTable/Index'
import NormalDetailModal from './components/NormalDetailModal'
import ElectronicResultModal from './components/ElectronicResultModal'
import ELectronicDetailModal from './components/ElectronicDetailModal'
import NormalModal from './components/NormalModal/Index'
import OtherModal from './components/OtherModal/Index'
import ArbitratorModal from './components/ArbitratorModal/Index'
import EmsModal from './components/EmsModal/Index'
import Common from '@js/common'

const { TabPane } = Tabs
const { confirm } = Modal

// 初始化地址
async function initAddress (caseid, dispatch) {
  const [e, d] = await awaitWrap(getAddressListRequest(caseid))
  if (e) {
    return message.error(e.message)
  }
  dispatch({ type: 'addressList', data: d })
}

// 初始化电子地址
async function initElectronicAddress (caseid, dispatch) {
  const [e, d] = await awaitWrap(getAddressListRequest(caseid, '电子地址'))
  if (e) {
    return message.error(e.message)
  }
  dispatch({ type: 'electronicAddressList', data: d })
}

// 编辑标签
function onEdit (targetKey, action, state, dispatch, caseid) {
  if (action === 'add') {
    dispatch({ type: 'addThemeModalVisible', data: true })
  } else if (action === 'remove') {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: `您确定要删除 ${state.paneMap[targetKey]} 吗？`,
      onOk: () => {
        delThemeHandle(targetKey, caseid, state.activeKey, dispatch)
      }
    })
  }
}

// 删除主题
async function delThemeHandle (targetKey, caseid, activeKey, dispatch) {
  const hide = message.loading('删除中', 120)
  const [e] = await awaitWrap(delThemeRequest(targetKey))
  hide()
  if (e) {
    return message.error(e.message)
  }
  initTheme(caseid, dispatch, activeKey)
}

// 添加主题
async function addThemeHandle (data, state, caseid, dispatch) {
  const hide = message.loading('提交中')
  const [e] = await awaitWrap(addThemeRequest(data, caseid))
  hide()
  if (e) {
    return message.error(e.message)
  }
  dispatch({ type: 'addThemeModalVisible', data: false })
  initTheme(caseid, dispatch, state.activeKey)
}

// 初始化字典
async function initDictionarys (dispatch) {
  const [e, d] = await awaitWrap(getDictionaryRequest())
  if (e) {
    return message.error(e.message)
  }
  dispatch({ type: 'dictionaries', data: d })
}

// 初始化主题
async function initTheme (caseid, dispatch, activeKey = '', refreshCaseData = () => {}) {
  const [e, d] = await awaitWrap(getThemeListRequest(caseid))
  if (e) {
    return message.error(e.message)
  }
  let hasKey = false
  const paneMap = {}
  const panes = d.map(li => {
    if (!hasKey) {
      hasKey = li.id === activeKey
    }
    paneMap[li.id] = li.name
    return {
      ...li,
      title: li.name,
      key: li.id
    }
  })
  dispatch({ type: 'panes', data: panes })
  dispatch({ type: 'paneMap', data: paneMap })
  if (!hasKey && panes.length) {
    dispatch({ type: 'activeKey', data: panes[0].key })
    dispatch({ type: 'currentTheme', data: panes[0] })
  }
  refreshCaseData()
}

// 初始化人员列表
async function initStaffs (dispatch) {
  const [e, d] = await awaitWrap(getStaffsRequest())
  if (e) {
    return message.error(e.message)
  }
  dispatch({ type: 'staffs', data: d })
}

// 获取公证人员列表
async function initNotaries (dispatch) {
  const [e, d] = await awaitWrap(getNotariesRequest())
  if (e) {
    return message.error(e.message)
  }
  dispatch({ type: 'notaries', data: d })
}

// 获取案件仲裁员列表
async function initArbitrators (caseid, dispatch) {
  const [e, d] = await awaitWrap(getArbitratorsRequest(caseid))
  if (e) {
    return message.error(e.message)
  }
  dispatch({ type: 'arbitrators', data: d })
}

// 初始化数据
function initData (caseDetail, dispatch) {
  const hide = message.loading('加载中')
  Promise.all([initDictionarys(dispatch), initTheme(caseDetail.id, dispatch), initStaffs(dispatch), initNotaries(dispatch), initArbitrators(caseDetail.id, dispatch)])
    .then(() => {
      hide()
    })
    .catch(e => {
      console.error(e)
      hide()
    })
}

// 隐藏弹框
function hideModal (type, dispatch) {
  dispatch({ type, data: false })
  dispatch({ type: 'currentTheme', data: null })
}

// 改变当前主题
function changeCurrentTheme (k, dispatch, list) {
  dispatch({ type: 'activeKey', data: k })
  for (let i = 0; i < list.length; i++) {
    const p = list[i]
    if (p.key === k) {
      dispatch({ type: 'currentTheme', data: p })
      break
    }
  }
}

// 刷新地址
function refreshAddress (caseDetail, dispatch) {
  const hide = message.loading('加载中', 120)
  Promise.all([initAddress(caseDetail.id, dispatch), initElectronicAddress(caseDetail.id, dispatch)])
    .then(() => {
      hide()
    })
    .catch(() => {
      hide()
    })
}

function Main ({ caseDetail = {}, refreshCaseData = () => {}, editable }) {
  const [state, dispatch] = useReducer(reducer, initialState)
  const [common, setCommon] = useState(null)
  const hide = k => dispatch({ type: k, data: false })
  useEffect(() => {
    initData(caseDetail, dispatch)
    const c = new Common()
    setCommon(c)
    refreshAddress(caseDetail, dispatch)
  }, [caseDetail])
  return (
    <div className={style.container}>
      <AddThemeModal visible={state.addThemeModalVisible} hide={() => hide('addThemeModalVisible')} onFinish={(d) => addThemeHandle(d, state, caseDetail.id, dispatch)} />
      <FinishThemeModal visible={state.finishThemeModalVisible} theme={state.currentTheme} hide={() => hideModal('finishThemeModalVisible', dispatch)} onFinish={() => initTheme(caseDetail.id, dispatch, state.activeKey, refreshCaseData)} />
      <NormalDetailModal visible={state.normalDetailModalVisible} data={state.currentService} hide={() => hide('normalDetailModalVisible')} />
      <ELectronicDetailModal visible={state.electronicDetailVisible} data={state.currentService} hide={() => hide('electronicDetailVisible')} />
      <ElectronicResultModal visible={state.electronicResultVisible} data={state.currentService} hide={() => hide('electronicResultVisible')} refreshCurrentTableFn={state.refreshCurrentTableFn} dictionaries={state.dictionaries} caseDetail={caseDetail} theme={state.currentTheme} common={common} pDispatch={dispatch} editable={editable} />
      <NormalModal visible={state.normalModalVisible} pState={state} data={state.currentService} hide={() => hide('normalModalVisible')} refreshCurrentTableFn={state.refreshCurrentTableFn} dictionaries={state.dictionaries} caseDetail={caseDetail} theme={state.currentTheme} common={common} pDispatch={dispatch} />
      <OtherModal visible={state.otherModalVisible} pState={state} data={state.currentService} hide={() => hide('otherModalVisible')} refreshCurrentTableFn={state.refreshCurrentTableFn} dictionaries={state.dictionaries} caseDetail={caseDetail} theme={state.currentTheme} pDispatch={dispatch} />
      <ArbitratorModal visible={state.arbitratorModalVisible} pState={state} data={state.currentService} hide={() => hide('arbitratorModalVisible')} refreshCurrentTableFn={state.refreshCurrentTableFn} dictionaries={state.dictionaries} caseDetail={caseDetail} theme={state.currentTheme} pDispatch={dispatch} />
      <EmsModal visible={state.emsModalVisible} pState={state} data={state.currentService} hide={() => hide('emsModalVisible')} refreshCurrentTableFn={state.refreshCurrentTableFn} refreshCurrentServiceFn={state.refreshCurrentServiceFn} dictionaries={state.dictionaries} caseDetail={caseDetail} theme={state.currentTheme} pDispatch={dispatch} common={common} editable={editable} />
      <Tabs
        onChange={k => changeCurrentTheme(k, dispatch, state.panes)}
        activeKey={state.activeKey}
        type='editable-card'
        onEdit={(targetKey, action) => onEdit(targetKey, action, state, dispatch, caseDetail.id)}
      >
        {state.panes.map(pane => {
          return (
            <TabPane tab={`${pane.title}${pane.type === '自定义送达' ? '(自定义)' : ''}`} key={pane.key}>
              <MainTable pState={state} pDispatch={dispatch} theme={pane} caseDetail={caseDetail} reloadTheme={() => initTheme(caseDetail.id, dispatch, state.activeKey)} refreshCaseData={refreshCaseData} editable={editable} common={common} refreshAddress={() => refreshAddress(caseDetail, dispatch)} />
            </TabPane>
          )
        })}
      </Tabs>
    </div>
  )
}

export default Main
